import { App } from 'vue';
import { request, router } from '@boeyo/portal';
import '@boeyo/portal/dist/style.css';
import { download } from '@boeyo/shared';
import '@boeyo/ui/dist/es/ui.css';
import { createHead } from '@unhead/vue/client';
import { message } from 'ant-design-vue';
import { AxiosResponse } from 'axios';
import './styles/index.css';

export { default as layout } from './layout';

export const systemTitle = '重大工程地震监测平台';

export const whiteNameList = ['/custom-login', '/license'];

export const loginPath = '/custom-login';

export const beforeMount = (app: App) => {
  app.use(createHead());
};

request.interceptors.response.use(
  (response): AxiosResponse<any, any> | Promise<AxiosResponse<any, any>> => {
    if (response.data?.code === 501) {
      router.push('/license');
    }
    if (
      response.config?.responseType === 'blob' &&
      (response.data.code ?? response.data instanceof Blob)
    ) {
      // 处理导出时后端返回错误信息
      if (response.data.type == 'application/json') {
        new Blob([response.data]).text().then((text) => {
          const result = JSON.parse(text);
          message.info(result.msg);
        });
        return Promise.reject();
      }
      const header = response.headers['content-disposition'];
      const match = header?.toLowerCase()?.match(/filename=([^;]+)/);
      if (match && !response.config.closeDownload) {
        const fileName = match[1];
        download(response.data, decodeURIComponent(fileName));
        return response;
      } else {
        console.log('未获取到文件名，已返回 blob，请自行处理');
        return response;
      }
    }

    return response;
  },
);
